home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 245 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: senior.nectec.or.th!nwg!finn
  2. From: finn@nwg.nectec.or.th (James Finn)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Friends....
  5. Date: 3 Jan 1996 08:59:28 GMT
  6. Organization: National Electronics and Computer Technology Center, Bangkok
  7. Message-ID: <4cdghg$1ep@senior.nectec.or.th>
  8. References: <4c9srh$g2l@ixnews3.ix.netcom.com>
  9. NNTP-Posting-Host: nwg.nectec.or.th
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Chris Morris (cpmorris@popd.ix.netcom.com) wrote:
  13. :     I am a beginner with C++ and have a question concerning the
  14. : declaration of 'friend' functions.
  15.  
  16. Question about why operator << is declared a friend instead of
  17. a member.
  18.  
  19. There is no other way to do it. Here is the problem.
  20. When an operator is defined as a member, the left
  21. operand must be a variable of the class type. In
  22. the case of
  23.  
  24.     cout << variable
  25.  
  26. the left operand is an ostream.
  27.  
  28. Say you have a class CL, with variables:
  29.  
  30.     CL cl1, cl2.
  31.  
  32. When you write
  33.  
  34.     cl1 + cl2
  35.  
  36. if operator + is defined as a member function, this compiles
  37. as
  38.     cl1.operator +(cl2)
  39.  
  40. If it's defined as a friend, it compiles as
  41.  
  42.     operator +(cl1, cl2)
  43.  
  44. Similarly, the only way << could be a member function
  45. is if it were a member function for the ostream class,
  46. since the left operand is the ostream. Since you
  47. can't (or don't want to) go mess with the source
  48. for the iostream library, you must define << as
  49. a friend function.
  50.  
  51. :     This is the confusing part.  How can the << and >> be used in the
  52. : definitions of << and >>?
  53.  
  54. Well, it's an overloaded function. The types being used in
  55. the function definition are not the same as the type for
  56. which the function is being defined. For example, if I
  57. were writing a << function to read complex numbers, I
  58. could use the fact that << is already defined to write
  59. real numbers. The complex << would write two doubles,
  60. using << to write them.
  61.  
  62. : Is seems like the new << and >> friend
  63. : functions are just defining their own implementations for handling the
  64. : user-defined type.  This is overloading, isn't it?
  65.  
  66. Exactly.
  67.  
  68. --James
  69.